package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.Person;
import com.lhdx.practical.bean.StudentGroup;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.service.StudentGroupService;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/function/StudentGroup")
public class StudentGroupController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StudentGroupService studentGroupService;
    @Autowired
    private PersonService personService;

    /**
     * 创建小组-页面
     * @return
     */
    @GetMapping("/addGroup")
    public ModelAndView addGroup() {
        return new ModelAndView("group/addGroup");
    }

    /**
     * 创建小组
     * @return
     */
    @CrossOrigin
    @PostMapping("/saveGroup")
    @ResponseBody
    public String saveGroup(String groupname,String groupintro) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            StudentGroup group = new StudentGroup(groupname,groupintro,person);
            //创建小组信息
            studentGroupService.save(group);
            //修改人员为创始人
            personService.updateIsJoin(userid,1);
            personService.updateGroupid(userid,group.getId(),group.getGroupname());
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"创建小组成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"创建小组失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 小组信息-页面
     * @return
     */
    @GetMapping("/groupInfo")
    public ModelAndView groupInfo(HttpServletResponse response) {
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        if(person.getGroupid() == 0){
            try {
                response.sendRedirect("grouplist");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }else{
            StudentGroup group = studentGroupService.findById(person.getGroupid());
            List<Person> personList = personService.findByGroupid(group.getId());
            return new ModelAndView("group/groupInfo")
                    .addObject("groupinfo",group)
                    .addObject("userid",userid)
                    .addObject("personList",personList);
        }
    }

    /**
     * 小组列表
     * @return
     */
    @GetMapping("/grouplist")
    public ModelAndView grouplist() {
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        List<StudentGroup> groups = studentGroupService.findAllByDepartid(person.getDepartid(),0);
        return new ModelAndView("group/grouplist")
                .addObject("groups",groups);
    }

    /**
     * 教师审核小组列表
     * @return
     */
    @GetMapping("/examineGrouplist")
    public ModelAndView examineGrouplist(long mid,long sid,long gradeid) {
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("gradeid",gradeid+"");
        PageVo<StudentGroup> pageResult = new PageVo<StudentGroup>(page,searchmap,studentGroupService.getResultList(0,-1,gradeid,page,Constants.pagesize));
        List<Person> persons = null;
        for(StudentGroup group : pageResult.getList()){
            group.setFoundername("（"+group.getGroupcount()+"人）");
            persons = personService.findByGroupid(group.getId());
            String str = "";
            for(Person p : persons){
                str += p.getRealname() + "、";
            }
            if(str.length() > 0){
                group.setGroupintro(str.substring(0,str.length()-1));
            }

        }
        return new ModelAndView("group/examineGrouplist")
                .addObject("pageResult",pageResult)
                .addObject("gradeid",gradeid)
                .addObject("mid",mid)
                .addObject("sid",sid);
    }

    /**
     * 教师小组审核
     * @param groupid  小组ID
     * @param state     审核状态 0 同意 1拒绝
     * @return
     */
    @CrossOrigin
    @PostMapping("/examineGroup")
    @ResponseBody
    public String examineGroup(long groupid,int state) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person teacher = personService.findById(userid);
            if(teacher != null && teacher.getType() == 1){
                if(state == 0){
                    //审核同意 更改状态
                    studentGroupService.updateState(groupid,2);
                }else{
                    //审核拒绝 遣散小组
                    //擦除所有小组成员信息
                    personService.updateCancelGroupid(groupid);
                    //删除小组
                    studentGroupService.deleteByID(groupid);
                }
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"审批成功","");
            }else {
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"审核失败，参数有误","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"审核失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 加入小组
     * @return
     */
    @CrossOrigin
    @PostMapping("/joinGroup")
    @ResponseBody
    public String joinGroup(long groupid) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = StrUtils.getLong(request,"userid",0);
            if(userid == 0){
                userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            }
            StudentGroup group = studentGroupService.findById(groupid);
            if(group == null){
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"加入小组失败-小组不存在","");
            }else{
                //修改人员为组员
                personService.updateIsJoin(userid,2);
                //更新学生绑定状态
                personService.updateGroupid(userid,groupid,group.getGroupname());
                //更新小组人数
                studentGroupService.updateGroupCount(groupid,group.getGroupcount()+1);
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"加入小组成功","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"加入小组失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 退出小组
     * @return
     */
    @CrossOrigin
    @PostMapping("/exitGroup")
    @ResponseBody
    public String exitGroup(long userid) {
        JSONObject jsonObject = new JSONObject();
        try {
            if(userid == 0){
                userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            }
            Person person = personService.findById(userid);
            if(person != null){
                //修改json状态为0 不加入任何小组
                personService.updateIsJoin(userid,0);
                //解除小组id
                personService.updateGroupid(userid,0,"");
                StudentGroup group = studentGroupService.findById(person.getGroupid());
                //更新小组人数
                studentGroupService.updateGroupCount(group.getId(),group.getGroupcount()-1);
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"退出小组成功","");
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"退出小组失败","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"退出小组失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 修改小组状态  小组状态 0小组创建 1提交审核 2审核通过
     * @return
     */
    @CrossOrigin
    @PostMapping("/updateState")
    @ResponseBody
    public String updateState(long groupid,int state) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            studentGroupService.updateState(groupid,state);
            if(person.getType() == 2){
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"小组提交申请成功,请耐心等待审核","");
            }else if(person.getType() == 1){
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"审核成功","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"状态更新失败","");
        }
        return jsonObject.toString();
    }
}
